import { defineStore } from 'pinia'

export interface IUserInfo {
  isAuthenticated: boolean
  userInfo: object
  permission: Array<string>
  token: string
  redirect: string
}
interface IState {
  user: IUserInfo[]
}
export const useAuthStore = defineStore({
  // state: () => {
  //   return { isAuthenticated: false, user: {}, permission: [], token: null }
  // },
  id: 'user',
  state: (): IState => ({
    user: JSON.parse(window.sessionStorage.getItem('user') as string) || {
      isAuthenticated: false,
      userInfo: {},
      permission: [],
      token: null,
      redirect: null
    }
  }),
  // getters: {
  //   isAuth: (state) => state.user.isAuthenticated,
  //   getUser: (state) => state.user.userInfo,
  //   getPermission: (state) => state.user.permission,
  //   getToken: (state) => state.user.token
  // },
  actions: {
    setStorage() {
      window.sessionStorage.setItem('user', JSON.stringify(this.user))
    },
    setAuth(isAuth: boolean) {
      if (isAuth) {
        this.user.isAuthenticated = isAuth
      } else {
        this.user.isAuthenticated = false
      }
      this.setStorage()
    },
    setUser(user: object | null) {
      if (user) {
        this.user.userInfo = user
      } else {
        this.user.userInfo = {}
      }
      this.setStorage()
    },
    setPermission(permission: Array<string> | null) {
      if (permission) {
        this.user.permission = permission
      } else {
        this.user.permission = []
      }
      this.setStorage()
    },
    setToken(token: string | null) {
      if (token) {
        this.user.token = token
      } else {
        this.user.token = null
      }
      this.setStorage()
    },
    setRedirect(redirect: string | null) {
      if (redirect) {
        this.user.redirect = redirect
      } else {
        this.user.redirect = null
      }
      this.setStorage()
    }
  }
})
